<template>
  <div class="app-container">
    <el-card>
      <!-- 试卷基本信息区域 -->
      <div class="paper-info">
        <h1 class="paper-title" v-if="paper.paperName">{{ paper.paperName }}</h1>
        <h1 class="paper-title" v-else>考试成绩查看</h1>
        <div class="paper-metadata">
          <div class="metadata-item">
            <span>学号：</span>
            <span>{{ student.studentId }}</span>
          </div>
          <div class="metadata-item">
            <span>姓名：</span>
            <span>{{ student.studentName }}</span>
          </div>
          <div class="metadata-item">
            <span>题目数：</span>
            <span>{{ allQuestions.length }}题</span>
          </div>
          <div class="metadata-item">
            <span>成绩：</span>
            <span class="score-value" :class="getScoreClass(calculateTotalScore(), paper.totalScore)">
              {{ calculateTotalScore().toFixed(1) }}/{{ paper.totalScore }}分
            </span>
          </div>
        </div>
      </div>

      <!-- 试卷内容区域 -->
      <div class="paper-content" v-loading="loading">
        <!-- 各题型分类显示 -->
        <!-- 单选题 -->
        <div v-if="singleChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getChineseNumber(getSectionIndex(0)) }}、单选题（共{{ singleChoiceQuestions.length }}题，共{{ getSectionScore(singleChoiceQuestions) }}分）</div>
          <div v-for="(question, index) in singleChoiceQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[单选题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <div class="options-list">
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex" class="option-item">
                    <el-radio v-model="question.student_answer" :label="option.value" disabled class="option-radio">
                      <span class="option-key">{{ option.label }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-radio>
                  </div>
                </div>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">我的答案：</div>
                <div class="answer-content answer-textarea" v-html="formatStudentAnswer(question)"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content mathjax-content" v-html="formatCorrectAnswer(question)"></div>
              </div>
              <!-- 得分显示 -->
              <div class="score-display">
                <div class="score-label">得分：</div>
                <div class="score-value">{{ question.student_score }}/{{ question.question_score }}分</div>
              </div>
              <!-- 题目解析 -->
              <div class="analysis-area">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content mathjax-content" v-html="question.analysis ? question.analysis : '无'"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 多选题 -->
        <div v-if="multiChoiceQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getChineseNumber(getSectionIndex(1)) }}、多选题（共{{ multiChoiceQuestions.length }}题，共{{ getSectionScore(multiChoiceQuestions) }}分）</div>
          <div v-for="(question, index) in multiChoiceQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[多选题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <div class="options-list">
                  <div v-for="(option, optIndex) in parseOptions(question.options)" :key="optIndex" class="option-item">
                    <el-checkbox :checked="isOptionSelected(question, option.value)" disabled class="option-checkbox">
                      <span class="option-key">{{ option.label }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">我的答案：</div>
                <div class="answer-content answer-textarea" v-html="formatStudentAnswer(question)"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content mathjax-content" v-html="formatCorrectAnswer(question)"></div>
              </div>
              <!-- 得分显示 -->
              <div class="score-display">
                <div class="score-label">得分：</div>
                <div class="score-value">{{ question.student_score }}/{{ question.question_score }}分</div>
              </div>
              <!-- 题目解析 -->
              <div class="analysis-area">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content mathjax-content" v-html="question.analysis ? question.analysis : '无'"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 判断题 -->
        <div v-if="judgmentQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getChineseNumber(getSectionIndex(2)) }}、判断题（共{{ judgmentQuestions.length }}题，共{{ getSectionScore(judgmentQuestions) }}分）</div>
          <div v-for="(question, index) in judgmentQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[判断题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
              <div class="options-container">
                <el-radio-group v-model="question.student_answer" disabled>
                  <el-radio label="1" class="option-radio">
                    <span class="option-key">A.</span>
                    <span class="option-content">正确</span>
                  </el-radio>
                  <el-radio label="0" class="option-radio">
                    <span class="option-key">B.</span>
                    <span class="option-content">错误</span>
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">我的答案：</div>
                <div class="answer-content answer-textarea" v-html="formatStudentAnswer(question)"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content mathjax-content" v-html="formatCorrectAnswer(question)"></div>
              </div>
              <!-- 得分显示 -->
              <div class="score-display">
                <div class="score-label">得分：</div>
                <div class="score-value">{{ question.student_score }}/{{ question.question_score }}分</div>
              </div>
              <!-- 题目解析 -->
              <div class="analysis-area">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content mathjax-content" v-html="question.analysis ? question.analysis : '无'"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 填空题 -->
        <div v-if="fillBlankQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getChineseNumber(getSectionIndex(3)) }}、填空题（共{{ fillBlankQuestions.length }}题，共{{ getSectionScore(fillBlankQuestions) }}分）</div>
          <div v-for="(question, index) in fillBlankQuestions" :key="question.question_id" 
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[填空题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">我的答案：</div>
                <div class="answer-content answer-textarea" v-html="formatStudentAnswer(question)"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content mathjax-content" v-html="formatFillAnswer(question.options)"></div>
              </div>
              <!-- 得分显示 -->
              <div class="score-display">
                <div class="score-label">得分：</div>
                <div class="score-value">{{ question.student_score }}/{{ question.question_score }}分</div>
              </div>
              <!-- 题目解析 -->
              <div class="analysis-area">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content mathjax-content" v-html="question.analysis ? question.analysis : '无'"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 简答题 -->
        <div v-if="shortAnswerQuestions.length > 0" class="question-section">
          <div class="section-title">{{ getChineseNumber(getSectionIndex(4)) }}、简答题（共{{ shortAnswerQuestions.length }}题，共{{ getSectionScore(shortAnswerQuestions) }}分）</div>
          <div v-for="(question, index) in shortAnswerQuestions" :key="question.question_id"
               class="question-item" :class="{'error-question': !question.is_correct}">
            <div class="question-content">
              <div class="question-title">
                <span class="question-index">{{ index + 1 }}.</span>
                <span class="question-type">[简答题]</span>
                <span class="question-score">({{ question.question_score }}分)</span>
              </div>
              <div class="question-text" v-html="question.question_content"></div>
            </div>
            <!-- 答案区域 -->
            <div class="answer-area">
              <div class="student-answer">
                <div class="answer-label">我的答案：</div>
                <div class="answer-content answer-textarea" v-html="formatStudentAnswer(question)"></div>
              </div>
              <div class="correct-answer">
                <div class="answer-label">参考答案：</div>
                <div class="answer-content mathjax-content" v-html="formatShortAnswer(question.question_answer)"></div>
              </div>
              <!-- 得分显示 -->
              <div class="score-display">
                <div class="score-label">得分：</div>
                <div class="score-value">{{ question.student_score }}/{{ question.question_score }}分</div>
              </div>
              <!-- 题目解析 -->
              <div class="analysis-area">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content mathjax-content" v-html="question.analysis ? question.analysis : '无'"></div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 教师评语 -->
        <div class="remark-area" v-if="remark">
          <div class="remark-title">教师评语：</div>
          <div class="remark-content" v-html="formatRemark(remark)"></div>
        </div>
        
        <div class="button-container">
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { getAnswerDetail } from '@/api/manage/mark';
import useUserStore from '@/store/modules/user';
import { getStudentByNumber } from '@/api/manage/student';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const loading = ref(true);
const answerId = ref('');
const questionList = ref([]);
const remark = ref('');

// 添加题型序号计数
let sectionIndex = 0;

const paper = reactive({
  paperName: '',
  totalScore: 0
});
const student = reactive({
  studentId: '',
  studentName: '',
  className: '',
  submitTime: '',
  examTime: '',
  totalScore: 0
});

// 计算题目分类
const singleChoiceQuestions = computed(() => questionList.value.filter(q => q.question_type === 0));
const multiChoiceQuestions = computed(() => questionList.value.filter(q => q.question_type === 1));
const judgmentQuestions = computed(() => questionList.value.filter(q => q.question_type === 2));
const fillBlankQuestions = computed(() => questionList.value.filter(q => q.question_type === 3));
const shortAnswerQuestions = computed(() => questionList.value.filter(q => q.question_type === 4));
const allQuestions = computed(() => questionList.value);

// 初始化MathJax
const initMathJax = () => {
  if (window.MathJax) {
    try {
      console.log('开始渲染MathJax...');
      // 确保页面上所有新增的mathjax-content类的元素都被处理
      const elements = document.querySelectorAll('.mathjax-content, .question-text, .analysis-content');
      console.log('找到需要渲染MathJax的元素数量:', elements.length);
      
      if (window.MathJax.typeset) {
        window.MathJax.typeset();
        console.log('MathJax渲染完成');
      } else if (window.MathJax.Hub) {
        window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub]);
        console.log('MathJax(v2)渲染完成');
      }
    } catch (error) {
      console.error('MathJax渲染失败:', error);
    }
  } else {
    console.warn('MathJax未加载');
  }
};

// 渲染数学公式
const renderMathFormula = (content) => {
  if (!content) return '';
  // 返回原始内容，让MathJax处理
  console.log('处理数学公式内容:', content && content.length > 20 ? content.substring(0, 20) + '...' : content);
  return content;
};

// 检查答卷状态
const checkExamAnswerStatus = async (studentId, paperId) => {
  try {
    // 构建answerId
    const answerId = `${studentId}_${paperId}`;
    console.log('正在检查答卷状态，answerId:', answerId);
    
    // 获取答卷详情
    const response = await getAnswerDetail(answerId);
    console.log('答卷API返回数据:', response);
    
    // 如果正常返回数据
    if (response.code === 200 && response.data) {
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 检查数据中的批阅状态指标 - 尝试从多个字段确定批阅状态
        const firstItem = response.data[0];
        console.log('答卷首条数据:', firstItem);
        
        // 1. 尝试从paper_status字段获取批阅状态(对应后端SQL中的ea.status as paper_status)
        const paperStatus = firstItem.paper_status;
        console.log('答卷paper_status字段值:', paperStatus);
        
        if (paperStatus !== undefined && paperStatus !== null) {
          // 如果存在明确的paper_status字段，直接使用
          // 注意：这里要处理布尔值情况，后端返回true/false而非1/0
          const isGraded = paperStatus === 1 || paperStatus === '1' || paperStatus === true;
          console.log('通过paper_status字段判断批阅状态:', isGraded ? '已批阅' : '未批阅');
          return {
            exists: true,
            status: isGraded ? 1 : 0,
            data: response
          };
        }
        
        // 2. 检查status字段
        const statusField = firstItem.status;
        console.log('答卷status字段值:', statusField);
        
        if (statusField !== undefined && statusField !== null) {
          const isGraded = statusField === 1 || statusField === '1';
          console.log('通过status字段判断批阅状态:', isGraded ? '已批阅' : '未批阅');
          return {
            exists: true,
            status: isGraded ? 1 : 0,
            data: response
          };
        }
        
        // 3. 检查mark_status字段（可能是不同的变量名）
        if (firstItem.mark_status !== undefined) {
          const isGraded = firstItem.mark_status === 1 || firstItem.mark_status === '1';
          console.log('通过mark_status字段判断批阅状态:', isGraded ? '已批阅' : '未批阅');
          return {
            exists: true,
            status: isGraded ? 1 : 0,
            data: response
          };
        }
        
        // 4. 检查是否有分数信息（如果没有明确的状态字段）
        const hasScore = response.data.some(item => {
          const hasValidScore = item.student_score !== undefined && 
                              item.student_score !== null && 
                              item.student_score !== '';
          if (hasValidScore) {
            console.log('检测到题目有分数:', item.question_id, item.student_score);
          }
          return hasValidScore;
        });
        
        if (hasScore) {
          console.log('未找到明确状态字段，但检测到分数信息，判定为已批阅');
          return {
            exists: true,
            status: 1,
            data: response
          };
        }
        
        // 5. 检查是否有is_correct标记
        const hasCorrectMarks = response.data.some(item => {
          const hasCorrectMark = item.is_correct !== undefined && item.is_correct !== null;
          if (hasCorrectMark) {
            console.log('检测到题目有正确性标记:', item.question_id, item.is_correct);
          }
          return hasCorrectMark;
        });
        
        if (hasCorrectMarks) {
          console.log('未找到明确状态字段，但检测到正确性标记，判定为已批阅');
          return {
            exists: true,
            status: 1,
            data: response
          };
        }
        
        // 如果以上方法都无法确定，假设未批阅
        console.log('无法确定批阅状态，默认判定为未批阅');
        return {
          exists: true,
          status: 0,
          data: response
        };
      } else {
        // 空数组或非数组数据
        console.log('API返回数据格式异常或为空');
        return {
          exists: false,
          status: null,
          data: response
        };
      }
    } else {
      // 没有找到答卷记录或API返回错误
      console.log('未找到答卷记录或API返回错误');
      return {
        exists: false,
        status: null,
        data: null
      };
    }
  } catch (error) {
    console.error('检查答卷状态失败:', error);
    return {
      exists: false,
      status: null,
      error: error
    };
  }
};

// 获取答卷详情
const getDetail = async (studentId, paperId) => {
  loading.value = true;
  console.log('开始获取答卷详情, paperId:', paperId);
  
  try {
    // 1. 首先查询试卷基本信息
    try {
      // 直接导入getPaper函数，而不是getPaperDetail
      import('@/api/manage/paper').then(async paperApi => {
        console.log('正在获取试卷信息...');
        if (paperApi && paperApi.getPaper) {
          const paperRes = await paperApi.getPaper(paperId);
          console.log('试卷信息API返回:', paperRes);
          
          if (paperRes.code === 200 && paperRes.data) {
            paper.paperName = paperRes.data.paperName || paperRes.data.paper_name;
            paper.totalScore = paperRes.data.totalScore || paperRes.data.total_score;
            console.log('获取到试卷信息:', paper);
          } else {
            console.warn('获取试卷信息API返回异常状态:', paperRes);
          }
        } else {
          console.warn('paper API 模块中没有找到 getPaper 方法');
        }
      }).catch(err => {
        console.error('导入 paper API 失败:', err);
      });
    } catch (paperError) {
      console.error('获取试卷信息失败:', paperError);
    }
    
    // 2. 获取学生信息
    try {
      const studentRes = await getStudentByNumber(studentId);
      console.log('学生信息API返回:', studentRes);
      if (studentRes.code === 200 && studentRes.data) {
        student.studentName = studentRes.data.studentName || studentRes.data.student_name || '未知';
        student.className = studentRes.data.className || studentRes.data.class_name || '未知';
        console.log('获取到学生信息:', student);
      }
    } catch (studentError) {
      console.error('获取学生信息失败:', studentError);
    }
    
    // 检查答卷状态
    const answerStatus = await checkExamAnswerStatus(studentId, paperId);
    
    // 如果答卷不存在
    if (!answerStatus.exists) {
      ElMessage.warning('未找到答题记录，请先完成考试');
      loading.value = false;
      return false;
    }
    
    // 如果答卷未批阅 - 不再重复检查分数情况，直接使用status字段判断
    if (answerStatus.status === 0) {
      ElMessage.warning('试卷暂未批阅，请等待教师批阅后查看');
      loading.value = false;
      return false;
    }
    
    // 有答卷且已批阅，显示详情
    const response = answerStatus.data;
    
    if (response.data && response.data.length > 0) {
      const firstItem = response.data[0];
      
      // 更新学生信息
      student.studentId = studentId;
      if (!student.studentName || student.studentName === '未知') {
        student.studentName = firstItem.student_name || '未知';
      }
      if (!student.className || student.className === '未知') {
        student.className = firstItem.class_name || '未知';
      }
      student.submitTime = firstItem.submit_time || '-';
      student.examTime = firstItem.exam_time || '-';
      student.totalScore = firstItem.paper_total_score || 0;
      
      // 如果前面获取试卷信息失败，再从答卷信息中获取
      if (!paper.paperName || paper.paperName.trim() === '') {
        paper.paperName = firstItem.paper_name || '';
        console.log('从答卷信息中获取试卷名称:', paper.paperName);
      }
      if (!paper.totalScore) {
        paper.totalScore = firstItem.paper_total_score || 0;
      }
      
      console.log('最终加载的试卷信息:', paper);
      
      // 处理问题列表
      questionList.value = response.data.map(item => {
        // 渲染题目内容数学公式
        const questionContent = renderMathFormula(item.question_content);
        // 渲染题目解析数学公式
        const analysis = renderMathFormula(item.analysis);
        
        // 为多选题创建选项数组
        const selectedOptions = [];
        if (item.question_type == 1 && item.student_answer) {
          const answers = item.student_answer.split(',');
          const options = parseOptions(item.options);
          
          // 初始化选项选中状态
          options.forEach(option => {
            selectedOptions.push(answers.includes(option.value));
          });
        }
        
        // 处理判断题答案格式
        let processedStudentAnswer = item.student_answer;
        if (item.question_type === 2 && item.student_answer) {
          // 判断题答案可能是A/B或1/0或true/false格式，需要标准化
          processedStudentAnswer = standardizeJudgmentAnswer(item.student_answer);
        }
        
        // 处理判断题正确答案格式
        let processedQuestionAnswer = item.question_answer;
        if (item.question_type === 2 && item.question_answer) {
          // 判断题正确答案也需要标准化
          processedQuestionAnswer = standardizeJudgmentAnswer(item.question_answer);
        }
        
        // 确保分数在有效范围内
        const studentScore = parseFloat(item.student_score || 0);
        const questionScore = parseFloat(item.question_score || 0);
        const finalStudentScore = Math.min(Math.max(0, studentScore), questionScore).toFixed(1);
        
        // 确保is_correct的判断与得分一致 - 只有满分才算对
        const isCorrect = studentScore === questionScore;
        
        return {
          ...item,
          question_content: questionContent,
          analysis: analysis,
          is_correct: isCorrect,
          student_score: finalStudentScore,
          question_score: questionScore.toFixed(1),
          selectedOptions: selectedOptions,
          student_answer: processedStudentAnswer,
          question_answer: processedQuestionAnswer
        };
      });
      
      // 从第一条记录中获取评语
      if (response.data && response.data.length > 0) {
        remark.value = response.data[0].remark || '';
      }
      
      // 在数据加载完成后渲染数学公式
      setTimeout(() => {
        initMathJax();
      }, 300);
      
      loading.value = false;
      return true;
    } else {
      ElMessage.error('获取答卷详情失败');
      loading.value = false;
      return false;
    }
  } catch (error) {
    console.error('获取答卷详情失败:', error);
    ElMessage.error('获取答卷详情失败');
    loading.value = false;
    return false;
  }
};

// 解析选项
const parseOptions = (optionsString) => {
  if (!optionsString) return [];
  
  return optionsString.split('|').map(opt => {
    // 查找第一个点的位置作为标签分隔符
    const dotIndex = opt.indexOf('.');
    if (dotIndex === -1) return { label: '', content: opt, value: '' };
    
    const label = opt.substring(0, dotIndex);
    // 保留内容的完整格式，不做额外处理
    const content = opt.substring(dotIndex + 1);
    
    return {
      label: label,
      content: content,
      value: label
    };
  });
};

// 检查选项是否被选中
const isOptionSelected = (question, optionValue) => {
  if (!question.student_answer) return false;
  return question.student_answer.split(',').includes(optionValue);
};

// 获取题型名称
const getQuestionTypeName = (type) => {
  const typeMap = {
    0: "单选题",
    1: "多选题",
    2: "判断题",
    3: "填空题",
    4: "简答题"
  };
  return typeMap[type] || "未知类型";
};

// 格式化学生答案
const formatStudentAnswer = (question) => {
  if (!question.student_answer) return '(未作答)';
  
  if (question.question_type === 0) {
    // 单选题 - 只返回选择的选项
    return question.student_answer;
  } else if (question.question_type === 1) {
    // 多选题 - 返回所有选择的选项，用逗号分隔
    return question.student_answer;
  } else if (question.question_type === 2) {
    // 判断题 - 转换为"正确"或"错误"
    return formatJudgmentAnswer(question.student_answer);
  } else if (question.question_type === 3) {
    // 填空题答案不做特殊处理，保持原样
    return question.student_answer;
  } else {
    return question.student_answer;
  }
};

// 格式化正确答案
const formatCorrectAnswer = (question) => {
  if (!question.question_answer) return '(无答案)';
  
  if (question.question_type === 0) {
    return formatSingleChoiceAnswer(question.question_answer);
  } else if (question.question_type === 1) {
    return formatMultipleChoiceAnswer(question.question_answer);
  } else if (question.question_type === 2) {
    return formatJudgmentAnswer(question.question_answer);
  } else if (question.question_type === 3) {
    // 填空题答案直接使用formatFillAnswer方法处理
    return formatFillAnswer(question.options);
  } else {
    return question.question_answer;
  }
};

// 格式化单选题答案
const formatSingleChoiceAnswer = (answer) => {
  return answer || '';
};

// 格式化多选题答案
const formatMultipleChoiceAnswer = (answer) => {
  return answer || '';
};

// 格式化判断题答案
const formatJudgmentAnswer = (answer) => {
  if (!answer) return '';
  
  // 支持多种格式：1/0, A/B, true/false
  if (answer === '1' || answer === 'A' || answer === 'true') {
    return '正确';
  } else {
    return '错误';
  }
};

// 格式化填空题学生答案
const formatFillBlankAnswer = (answer) => {
  if (!answer) return '(未作答)';
  // 只处理HTML特殊字符，不替换逗号为分号
  return answer.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
};

// 格式化填空题正确答案
const formatFillAnswer = (optionsString) => {
  if (!optionsString) return '(无答案)';
  
  // 直接显示后端已处理好的选项字符串，确保MathJax正确渲染
  setTimeout(() => {
    initMathJax();
  }, 100);
  
  return optionsString;
};

// 格式化简答题参考答案
const formatShortAnswer = (answer) => {
  if (!answer) return '(无参考答案)';
  return answer;
};

// 获取分数样式类
const getScoreClass = (score, totalScore) => {
  if (!score || !totalScore) return 'score-fail';
  
  const percentage = (parseFloat(score) / parseFloat(totalScore)) * 100;
  
  if (percentage >= 90) {
    return 'score-excellent';
  } else if (percentage >= 80) {
    return 'score-good';
  } else if (percentage >= 60) {
    return 'score-pass';
  } else {
    return 'score-fail';
  }
};

// 获取题型总分
const getSectionScore = (questions) => {
  return questions.reduce((sum, q) => sum + parseFloat(q.question_score || 0), 0);
};

// 计算总分
const calculateTotalScore = () => {
  return questionList.value.reduce((sum, q) => sum + parseFloat(q.student_score || 0), 0);
};

// 返回
const goBack = () => {
  router.go(-1);
};

// 格式化用时
const formatExamTime = (examTime) => {
  if (!examTime) return '-';
  
  // 如果已经是格式化好的字符串，如"3小时29分7秒"，直接返回
  if (typeof examTime === 'string' && (examTime.includes('小时') || examTime.includes('分') || examTime.includes('秒'))) {
    return examTime;
  }
  
  // 如果是 HH:MM:SS 格式
  if (typeof examTime === 'string' && examTime.includes(':')) {
    const parts = examTime.split(':');
    if (parts.length === 3) {
      const hours = parseInt(parts[0]);
      const minutes = parseInt(parts[1]);
      const seconds = parseInt(parts[2]);
      
      let result = '';
      if (hours > 0) {
        result += hours + '小时';
      }
      if (minutes > 0 || hours > 0) {
        result += minutes + '分';
      }
      result += seconds + '秒';
      
      return result;
    }
  }
  
  return examTime;
};

// 标准化判断题答案格式
const standardizeJudgmentAnswer = (answer) => {
  if (answer === 'A' || answer === 'true' || answer === '1') {
    return '1';
  } else if (answer === 'B' || answer === 'false' || answer === '0') {
    return '0';
  }
  return answer;
};

// 计算各题型序号的函数
const getSectionIndex = (questionType) => {
  // 重置序号计数
  sectionIndex = 0;
  
  // 按题型顺序计算序号
  if (singleChoiceQuestions.value.length > 0) sectionIndex++;
  if (questionType === 0) return sectionIndex;
  
  if (multiChoiceQuestions.value.length > 0) sectionIndex++;
  if (questionType === 1) return sectionIndex;
  
  if (judgmentQuestions.value.length > 0) sectionIndex++;
  if (questionType === 2) return sectionIndex;
  
  if (fillBlankQuestions.value.length > 0) sectionIndex++;
  if (questionType === 3) return sectionIndex;
  
  if (shortAnswerQuestions.value.length > 0) sectionIndex++;
  if (questionType === 4) return sectionIndex;
  
  return 0;
};

// 将数字转换为中文序号
const getChineseNumber = (num) => {
  const chineseNumbers = ['一', '二', '三', '四', '五'];
  return chineseNumbers[num - 1] || num;
};

// 格式化教师评语，处理HTML标签
const formatRemark = (remark) => {
  if (!remark) return '';
  
  // 如果评语中包含HTML标签（如<p>标签），则返回原始内容由v-html渲染
  // 否则进行换行处理
  if (/<[a-z][\s\S]*>/i.test(remark)) {
    return remark;
  } else {
    return remark.replace(/\n/g, '<br>');
  }
};

// 初始化
onMounted(async () => {
  try {
    // 从路由参数中获取paperId
    const paperId = route.query.paperId;
    
    if (!paperId) {
      ElMessage.error('缺少必要的参数');
      loading.value = false;
      return;
    }
    
    // 加载MathJax
    loadMathJax();
    
    // 获取用户信息
    const userInfo = await userStore.getInfo();
    
    // 确定学生ID
    let studentId = '';
    
    // 如果是管理员，使用默认学号
    if (userStore.roles.includes('admin')) {
      studentId = '1000000001'; // 管理员模拟学生
    } else if (userInfo && userInfo.user && userInfo.user.userName) {
      studentId = userInfo.user.userName;
    } else {
      ElMessage.error('获取用户信息失败');
      loading.value = false;
      return;
    }
    
    // 显示答卷详情
    const success = await getDetail(studentId, paperId);
    
    // 如果失败，清空页面内容
    if (!success) {
      questionList.value = [];
    }
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('加载成绩查看页面失败');
    loading.value = false;
  }
});

// 加载MathJax
const loadMathJax = () => {
  if (window.MathJax) {
    console.log('MathJax已加载');
    initMathJax(); // 确保页面加载时立即尝试初始化
    return;
  }
  
  console.log('正在加载MathJax...');
  const script = document.createElement('script');
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
  script.async = true;
  
  // 配置MathJax (必须在加载脚本前配置)
  window.MathJax = {
    tex: {
      inlineMath: [['$', '$'], ['\\(', '\\)']],
      displayMath: [['$$', '$$'], ['\\[', '\\]']],
      processEscapes: true
    },
    options: {
      enableMenu: false,
      skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre']
    },
    startup: {
      ready: () => {
        console.log('MathJax就绪');
        window.MathJax.startup.defaultReady();
      }
    }
  };
  
  script.onload = () => {
    console.log('MathJax加载成功');
    // 加载完成后执行渲染
    setTimeout(() => {
      initMathJax();
    }, 300);
  };
  
  document.head.appendChild(script);
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.paper-info {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.paper-title {
  font-size: 24px;
  margin-bottom: 15px;
  text-align: center;
}

.paper-metadata {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-bottom: 10px;
}

.metadata-item {
  margin: 5px 10px;
  font-size: 14px;
}

.score-value {
  font-weight: bold;
}

.paper-content {
  margin-bottom: 20px;
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  padding: 10px;
  background-color: #ecf5ff;
  border-left: 5px solid #409EFF;
  margin-bottom: 20px;
  font-weight: bold;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  box-sizing: border-box;
}

.error-question {
  border: 2px solid #F56C6C;
  padding: 19px;
}

.question-content {
  margin-bottom: 15px;
}

.question-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-index {
  margin-right: 5px;
  font-weight: bold;
}

.question-type {
  margin-right: 10px;
  color: #409EFF;
}

.question-score {
  margin-left: 10px;
  color: #303133;
}

.options-container {
  margin-bottom: 20px;
}

.options-list {
  padding-left: 20px;
}

.option-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.option-key {
  margin-right: 10px;
  font-weight: bold;
  min-width: 20px;
}

.option-content {
  flex: 1;
}

.answer-area {
  border-top: 1px solid #eee;
  padding-top: 15px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.student-answer, .correct-answer, .score-display {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  align-items: flex-start;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
  min-width: 90px;
  display: inline-block;
}

.answer-content {
  color: #606266;
  word-break: break-all;
  margin-bottom: 10px;
  flex: 1;
  display: inline-block;
}

.answer-content.answer-textarea {
  white-space: pre-wrap;
}

.score-display {
  margin-top: 5px;
}

.score-label {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
}

.score-value {
  font-weight: bold;
  display: inline-block;
}

.score-excellent {
  color: #67c23a;
}

.score-good {
  color: #409eff;
}

.score-pass {
  color: #303133;
}

.score-fail {
  color: #f56c6c;
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.remark-area {
  margin: 30px 0 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border-left: 5px solid #409EFF;
}

.remark-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #409EFF;
  font-size: 16px;
}

.remark-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-line;
}

/* 数学公式样式 */
.mathjax-content {
  max-width: 100%;
  padding: 5px 0;
  overflow: hidden;
}

:deep(.MathJax) {
  max-width: 100%;
  overflow: hidden !important;
}

:deep(.mjx-chtml) {
  max-width: 100%;
  overflow: hidden !important;
  padding: 5px 0;
}

:deep(.mjx-math) {
  max-width: 100%;
  overflow: hidden !important;
}

.question-text {
  margin-bottom: 15px;
  word-break: break-word;
}

:deep(.question-text img) {
  max-width: 100%;
  height: auto;
}

:deep(.answer-content img) {
  max-width: 100%;
  height: auto;
}

:deep(.el-radio), :deep(.el-checkbox) {
  width: 100%;
  margin-right: 0;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

:deep(.el-radio__label), :deep(.el-checkbox__label) {
  white-space: normal;
  padding-left: 8px;
  display: flex;
  align-items: center;
}

.analysis-area {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
  width: 100%;
  display: flex;
  align-items: flex-start;
}

.analysis-label {
  font-weight: bold;
  color: #67C23A;
  margin-right: 10px;
  min-width: 50px;
}

.analysis-content {
  flex: 1;
  line-height: 1.6;
  color: #606266;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
}
</style>